// asyncPackageComponent/components/yz_supplyAddrMatcher/index.js
let app = getApp();

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    // 是否显示弹出层
    visible: {
      type: Boolean,
      value: false,
      observer(newVal) {
        // 当属性值变化时的处理
        console.log('visible changed:', newVal);
      }
    },
    addr: {
      type: null,
      value: {}
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    show: false,

    cascaderValuePop: false,
    fieldText: "",
    fieldNames: {
      text: "name",
      value: "id"
    },
    cascaderValue: "",
    cascaderOptions: []
  },
  // 监听数据变化
  observers: {
    'visible': function(value) {
      // 当 visible 属性变化时，同步更新内部的 show 数据
      this.setData({
        show: value
      });
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    async getRegionList() {
      if(this.data.cascaderOptions.length > 0) {
        this.setData({
          cascaderValuePop: true
        })
        return
      };
      let response = await app._postNetWork({
        url: app.getNetAddresss('plugin.yz-supply.frontend.index.index.getRegionList'),
        data: {}
      });
      let {
        result,
        msg,
        data
      } = response.data;
      if (!result) return app.tips(msg);

      this.data.cascaderOptions = data.data.map((item, index) => ({
        ...item,
        index: index,
        children: [] // 初始化子节点
      }));
      this.setData({
        cascaderOptions: this.data.cascaderOptions,
        cascaderValuePop: true
      })
    },
    async onChange(e) {
      const {
        value,
        selectedOptions,
        tabIndex
      } = e.detail;
      const firstIndex = selectedOptions[0].index;
      const secondIndex = selectedOptions[1]?selectedOptions[1].index : 0;
      const thirdIndex = selectedOptions[2]?selectedOptions[2].index : 0;
      const newData = {};

      if (tabIndex == 0 && this.data.cascaderOptions[selectedOptions[tabIndex].index].children.length == 0) {
        let response = await app._postNetWork({
          url: app.getNetAddresss('plugin.yz-supply.frontend.index.index.getRegionList'),
          data: {
            parent_id: value
          }
        });
        let {
          result,
          msg,
          data
        } = response.data;
        if (!result) return app.tips(msg);

        this.data.cascaderOptions[selectedOptions[0].index].children = data.data.map((item, index) => ({
          ...item,
          index: index,
          children: [] // 初始化子节点
        }));
      
        // 构建要更新的数据对象
        const newData = {};
        const key = `cascaderOptions[${firstIndex}].children`;
        newData[key] = data.data.map((item, index) => ({
          ...item,
          index: index,
          children: []
        }));

        // 使用 setData 更新数据
        this.setData(newData);
      } else if (tabIndex === 1) {
        let response = await app._postNetWork({
          url: app.getNetAddresss('plugin.yz-supply.frontend.index.index.getRegionList'),
          data: {
            parent_id: value
          }
        });
        let {
          result,
          msg,
          data
        } = response.data;
        if (!result) return app.tips(msg);

        this.data.cascaderOptions[selectedOptions[0].index].children[selectedOptions[1].index].children = data.data.map((item, index) => ({
          ...item,
          index: index,
          children: [] // 初始化子节点
        }));
        // 第二层级的更新
        const key1 = `cascaderOptions[${firstIndex}].children[${secondIndex}].children`;
        newData[key1] = data.data.map((item, index) => ({
          ...item,
          index: index,
          children: []
        }));

        this.setData(newData);
      } else if (tabIndex === 2) {
        let response = await app._postNetWork({
          url: app.getNetAddresss('plugin.yz-supply.frontend.index.index.getRegionList'),
          data: {
            parent_id: value
          }
        });
        let {
          result,
          msg,
          data
        } = response.data;
        if (!result) return app.tips(msg);

        this.data.cascaderOptions[selectedOptions[0].index].children[selectedOptions[1].index].children[selectedOptions[2].index].children = data.data.map((item, index) => ({
          ...item
        }));
        // 第三层级的更新
        const key2 = `cascaderOptions[${firstIndex}].children[${secondIndex}].children[${thirdIndex}].children`;
        newData[key2] = data.data.map((item, index) => ({
          ...item
        }));

        this.setData(newData);
      }
    },
    onFinish(e) {
      const {
        selectedOptions,
        value
      } = e.detail;
      let newData = {};
      newData.cascaderValuePop = false;
      newData.fieldValue = selectedOptions.map(option => option.id);
      newData.fieldTextArr = selectedOptions.map(option => option.name);
      newData.fieldText = selectedOptions.map(option => option.name).join("/");
      this.setData(newData);
    },

    async submitMatcher() {
      if (this.data.fieldValue.length == 0) {
        app.tips("请选择地址");
        return;
      }
      //需要将this.addr进行decodeURIComponent解码，并且JSON.parse
      let addr = {};
      try {
        addr = JSON.parse(decodeURIComponent(this.data.addr));
      } catch (error) {
        console.log(error);
      }
      let {
        province_id,
        city_id,
        district_id,
        street_id,
        province,
        city,
        district,
        street
      } = addr;
      let response = await app._postNetWork({
        url: app.getNetAddresss('plugin.yz-supply.frontend.index.index.createAddressMatching'),
        data: {
          province_id: province_id,
          city_id: city_id,
          district_id: district_id,
          street_id: street_id,
          middle_province_id: this.data.fieldValue[0],
          middle_city_id: this.data.fieldValue[1],
          middle_district_id: this.data.fieldValue[2],
          middle_street_id: this.data.fieldValue[3],
          province: province,
          city: city,
          district: district,
          street: street,
          middle_province: this.data.fieldTextArr[0],
          middle_city: this.data.fieldTextArr[1],
          middle_district: this.data.fieldTextArr[2],
          middle_street: this.data.fieldTextArr[3]
        }
      });
      let {
        result,
        msg,
        data
      } = response.data;
      if (!result) return app.tips(msg);
      this.triggerEvent('update:visible', false);
      this.triggerEvent('success');
    },
    onClone() {
      this.triggerEvent('close');
      this.triggerEvent('update:visible', false);
    },
    onClonecascader(){
      this.setData({
        cascaderValuePop: false
      })
    }
  }
})